
<template>
  <div>
    <a-spin :spinning="loading">
      <a-card
        :bordered="false"
        :bodyStyle="{ padding: '24px 0', height: '100%' }"
        id="aCardPosition"
      >
        <div class="table-page-search-wrapper">
          <a-row :gutter="48">
            <a-form layout="inline">
              <a-col :md="8" :sm="24">
                <a-form-item label="上课日期">
                  <a-range-picker :value="datevalue1" style="width:80%;" @change="handleChange1" />
                </a-form-item>
              </a-col>
              <a-col :md="8" :sm="24">
                <a-form-item label="所在班级">
                  <a-select
                    v-model="queryParam.class_id"
                    style="width:80%;"
                    placeholder="请选择所在班级"
                    allowClear
                  >
                    <a-select-option
                      v-for="(item,index) in Isclass"
                      :key="index"
                      :value="item.id"
                    >{{item.name}}</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :md="8" :sm="24">
                <a-form-item label="上课老师">
                  <a-select
                    v-model="queryParam.teacher_id"
                    style="width:80%;"
                    placeholder="请选择上课老师"
                    allowClear
                  >
                    <a-select-option
                      v-for="(item,index) in Isteacher"
                      :key="index"
                      :value="item.id"
                    >{{item.name}}</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-form-model v-if="showSearch" layout="inline" style="margin-top:10px;">
                <a-col :md="8" :sm="24">
                  <a-form-item label="点名日期:">
                    <a-range-picker :value="datevalue2" style="width:80%;" @change="handleChange2" />
                  </a-form-item>
                </a-col>
                <a-col :md="8" :sm="24">
                  <a-form-item label="授课课程">
                    <a-select
                      v-model="queryParam.course_id"
                      style="width:80%;"
                      placeholder="请选择授课课程"
                      allowClear
                    >
                      <a-select-option
                        v-for="(item,index) in Iscourses"
                        :key="index"
                        :value="item.id"
                      >{{item.name}}</a-select-option>
                    </a-select>
                  </a-form-item>
                </a-col>
              </a-form-model>
            </a-form>
          </a-row>
        </div>
        <a style="cursor:pointer" v-if="showSearch" @click="more" id="moreButton">
          收起
          <a-icon type="up"></a-icon>
        </a>
        <a style="cursor:pointer" v-if="!showSearch" @click="more" id="moreButton">
          展开
          <a-icon type="down"></a-icon>
        </a>

        <div class="table-operator">
          <a-button style @click="excelVisible=true">导出</a-button>（温馨提示：为了缩短导出时间，建议您提前对上课记录进行筛选）
        </div>
        <a-modal
          title="请选择导出形式"
          :visible="excelVisible"
          :footer="null"
          @cancel="excelVisible=false"
          width="640px"
          :bodyStyle="{padding:'10px'}"
        >
          <div class="excelModal">
            <div class="left">
              <img src="~@/assets/excelClass.png" width="170" height="170" alt />
              <br />
              <a-button style="margin:10px 0;" @click="excelOut('class')">按班级导出</a-button>
              <div
                style="width: 284px;color: #666;padding-left:20px;font-size: 14px;text-align: left;"
              >以班级为单位导出上课记录，可用于统计 班级课时/课消、老师授课课时/课消等。</div>
            </div>
            <div class="right">
              <img src="~@/assets/excelStudent.png" width="170" height="170" alt />
              <br />
              <a-button style="margin:10px 0;" @click="excelOut('student')">按学员导出</a-button>
              <div
                style="width: 284px;color: #666;padding-left:20px;font-size: 14px;text-align: left;"
              >以学员为单位导出上课记录，可用于统计 学员课时/课消，学员到课情况等。</div>
            </div>
          </div>
          <div
            style="text-align:center;margin-top: 60px;line-height: 20px;font-size: 12px;color: #999;"
          >系统单次支持导出10,000条数据</div>
        </a-modal>
        <s-table
          :columns="columns"
          :data="loadData"
          :rowKey="(record) => record.id"
          class="user_management_table"
          style="margin-top:20px;"
          ref="table"
          :pagination="pagination"
          :scroll="{ x: 1500}"
        >
          <span slot="time" slot-scope="text, record">
            {{record.attend_class_day}} {{record.start_time}}~{{record.end_time}}
            <a-icon
              type="edit"
              @click="timeEdit(record)"
              style="margin-left:20px;"
              v-if="record.class&&record.deleted_at===null"
            />
          </span>
          <span slot="sum_class_consume" slot-scope="text,record">
            <span v-if="record.sum_class_consume">￥{{record.sum_class_consume.toFixed(2)}}</span>
            <span v-else>暂无</span>
          </span>
          <span slot="class_" slot-scope="text, record">
            <span v-if="record.class">{{record.class.name||"--"}}</span>
            <span v-else>--</span>
          </span>
          <span slot="verify_class_hour" slot-scope="text,record">
            <span v-if="record.deleted_at!==null">已撤销</span>
            <span v-else-if="record.class_hour==record.verify_class_hour">正常</span>
            <span v-else-if="record.class_hour!=record.verify_class_hour">修改</span>
            <span v-else>--</span>
          </span>
          <span slot="actual_number" slot-scope="text, record">
            <a
              @click="openstudent(record)"
              :disabled="record.deleted_at!==null"
            >{{record.actual_number}}</a>
          </span>
          <span slot="classHour" slot-scope="text, record">
            <span>{{record.class_hour}}</span>&nbsp;&nbsp;->
            <span v-if="!IshourEdit">
              <span>{{record.verify_class_hour||record.class_hour}}</span>
              <a-icon
                type="edit"
                @click="hourEdit(record)"
                style="margin-left:20px;"
                v-if="record.deleted_at===null"
              />
            </span>
            <span v-else-if="IshourEdit&&IshourEdit_id!=record.id">
              <span>{{record.verify_class_hour||record.class_hour}}</span>
              <a-icon 
                type="edit"
                @click="hourEdit(record)"
                style="margin-left:20px;"
                v-if="record.deleted_at===null"
              />
            </span>
            <span v-if="IshourEdit&&IshourEdit_id==record.id">
              <a-input-number
                id="inputNumber"
                :min="0"
                v-model="record.verify_class_hour"
                @change="onChangeverify"
              />
              <a-icon type="save" @click="hourEdit(record)" style="margin-left:20px;"></a-icon>
            </span>
          </span>
          <span slot="action" slot-scope="text, record">
            <!-- <a @click="openstudent(record)">操作记录</a> -->
            <!-- <a-divider type="vertical" /> -->
            <a
              :disabled="record.deleted_at!==null"
              @click="table_del(record)"
            >撤销</a>
          </span>
        </s-table>
        <a-modal
          title="修改上课时间"
          v-model="visible"
          @ok="handleOk"
          @confirmLoading="changeTimeloading"
        >
          <p>
            上课日期:
            <a-date-picker
              @change="onChangedate"
              :defaultValue="moment(time_date.attend_class_day)"
            />
          </p>
          <p>
            上课时间:
            <a-time-picker
              @change="handleChangestart"
              :defaultValue="moment(time_date.start_time,'HH:mm')"
              format="HH:mm"
            />~
            <a-time-picker
              @change="handleChangeend"
              :defaultValue="moment(time_date.end_time,'HH:mm')"
              format="HH:mm"
            />
          </p>
        </a-modal>
        <a-modal
          :title="'签到名单'+modaltitle"
          v-model="tablevisible"
          :footer="null"
          @cancel="$refs.table.refresh()"
          :width="1300"
          :bodyStyle="{'padding-top':'10px','padding-bottom':'10px'}"
        >
          <a-spin :spinning="modalLoading">
            <!-- <a-button style="margin-right:10px;">添加临时学员</a-button>
            <a-button>添加补课学员</a-button>-->
            <a-table
              :columns="tablecolumns"
              :dataSource="tableData"
              :pagination="false"
              :rowKey="(record) => record.id"
              class="user_management_table"
              style="border:1px solid #e8e8e8;margin-top:10px;"
              :scroll="{y:600}"
              ref="table1"
            >
              <span slot="name" slot-scope="text, record">{{record.student.name}}</span>
              <span slot="phone" slot-scope="text, record">{{record.student.main_phone}}</span>
              <span slot="type" slot-scope="text, record">
                <span v-if="!record.flag">
                  <span v-if="record.type==1">到课</span>
                  <span v-if="record.type==2">迟到</span>
                  <span v-if="record.type==3">请假</span>
                  <span v-if="record.type==4">未到</span>
                </span>
                <span v-if="record.flag">
                  <a-select v-model="record.daotype" @change="$forceUpdate()" style="width:80px;">
                    <a-select-option :value="1">到课</a-select-option>
                    <a-select-option :value="2">迟到</a-select-option>
                    <a-select-option :value="3">请假</a-select-option>
                    <a-select-option :value="4">未到</a-select-option>
                  </a-select>
                </span>
              </span>
              <span slot="class_hour" slot-scope="text,record">
                <span v-if="record.consume_type==1">
                  <span v-if="!record.flag">
                    {{record.class_hour}}
                    <span
                      v-if="record.super_status==1"
                    >(超上{{record.go_beyond}}课时)</span>
                  </span>
                  <span v-else>
                    <a-input
                      v-model="record.class_hour"
                      onkeyup="this.value=this.value.replace(/\D/g,'')"
                      @change="changeClassHour(record)"
                      placeholder="请输入所扣课时"
                    ></a-input>
                    <span v-if="record.super_status==1">(超上{{record.go_beyond}}课时)</span>
                  </span>
                </span>
                <span v-else>按天自动消耗</span>
              </span>
              <span slot="remarks" slot-scope="text,record">
                <span v-if="!record.flag">{{record.remarks||'-'}}</span>
                <span v-else>
                  <a-input
                    v-model="record.remarks"
                    :max-length="200"
                    placeholder="最多输入200个字"
                    @change="$forceUpdate()"
                  ></a-input>
                </span>
              </span>
              <span slot="action" slot-scope="text,record,index">
                <span v-if="!record.flag">
                  <a @click="showOrHidden(record,index)" v-if="record.is_lock==2">修改</a>
                  <span
                    style="cursor: pointer; color: rgb(153, 153, 153);"
                    v-if="record.is_lock==1"
                  >
                    <a-tooltip>
                      <template slot="title">学员本次消耗课程已结课，不能修改</template>
                      不能修改
                    </a-tooltip>
                  </span>
                </span>
                <span v-else>
                  <a @click="saveStudentInfo(record)">保存</a>
                  <a-divider type="vertical" />
                  <a @click="showOrHidden(record,index)">取消</a>
                </span>
              </span>
            </a-table>
            <div style="margin-top:15px;display:flex;justify-content: space-between;align-items: center;">
              <span v-if="pageData&&pageData.pagination">共{{pageData.pagination.total}}条数据</span>
              <div>
                <a-pagination
                  v-if="pageData&&pageData.pagination"
                  v-model="nowPage"
                  :total="pageData.pagination.total"
                  @change="changePage"
                />
              </div>
            </div>
          </a-spin>
        </a-modal>
        <a-modal
          :visible="actionModelVisible"
          title="操作记录"
          @cancel="actionModelVisible=false"
          :footer="null"
          :width="1300"
        >
          <a-spin :spinning="modalLoading">
            <s-table
              class="user_management_table"
              style="margin-top:20px;"
              ref="actionTable"
              :columns="actionColumns"
              :data="actionData"
              :scroll="{y:500}"
            ></s-table>
          </a-spin>
        </a-modal>
      </a-card>
    </a-spin>
  </div>
</template>
<script>
import moment from 'moment'
import { STable, Ellipsis } from '@/components'
import CreateForm from '../../list/modules/CreateForm'
import { getRoleList, getServiceList } from '@/api/manage'
import {
  growthArchivesList,
  createAarchives,
  uploadPic,
  archivesDel,
  callRecords,
  editVerifyClassHour,
  editClassTime,
  callRecordsDelete,
  callRecordsStudentList,
  callRecordseEditType,
  editOrderInfo,
  orderNameExcelOut,
  orderNameExcelOutByClass,
} from '@/api/homeSchool'
import { classList } from '@/api/class'
import { growthTypeList } from '@/api/growth'
import { teacherList } from '@/api/teacher'
import { coursesList } from '@/api/courseCharge'

export default {
  name: 'TableList',
  components: {
    STable,
    Ellipsis,
    CreateForm,
    // StepByStepModal
  },
  data() {
    return {
      excelVisible: false,
      loading: false,
      modalLoading: false,
      modaltitle: '',
      new_attend_class_day: '',
      new_start_time: '',
      new_end_time: '',
      time_date: {},
      changeTimeloading: false,
      datevalue1: [],
      datevalue2: [],
      peopleId: '',
      isTypeEditType: true,
      isTypeEdit: '',
      isTypeEditId: '',
      IshourEdit: false,
      IshourEdit_id: '',
      showSearch: false, // 高级搜索 展开/关闭
      details: {}, //详情数据
      visible: false,
      tablevisible: false,
      advanced: false,
      // 课程数据
      Iscourses: [],
      // 老师数据
      Isteacher: [],
      // 班级数据
      Isclass: [],
      // delivery: true, //开关的值
      // 查询参数
      queryParam: {
        // project_type: 2 //1是学生,2是班级
        start_time: '',
        end_time: '',
        school_id: this.$store.state.user.school,
      },
      pagination:{
        showTotal:total=>`共${total}条数据`,
      },  
      tableData: [],
      nowPage:1,
      pageData:{},
      // 表头
      tablecolumns: [
        {
          title: '学员姓名',
          dataIndex: 'name',
          width: 150,
          align: 'center',
          scopedSlots: { customRender: 'name' },
        },
        {
          title: '手机号',
          dataIndex: 'phone',
          width: 150,
          align: 'center',
          scopedSlots: { customRender: 'phone' },
        },
        {
          title: '到课状态',
          dataIndex: 'type',
          width: 150,
          align: 'center',
          scopedSlots: { customRender: 'type' },
        },
        {
          title: '扣课时',
          dataIndex: 'class_hour',
          width: 180,
          align: 'center',
          scopedSlots: { customRender: 'class_hour' },
        },
        {
          title: '备注',
          dataIndex: 'remarks',
          ellipsis: true,
          scopedSlots: { customRender: 'remarks' },
        },
        {
          title: '操作',
          width: 200,
          dataIndex: 'action',
          align: 'center',
          scopedSlots: { customRender: 'action' },
        },
      ],
      // 表头
      columns: [
        {
          title: '点名时间',
          dataIndex: 'created_at',
          fixed: 'left',
          width:150
        },
        {
          title: '班级名称',
          dataIndex: 'class',
          scopedSlots: { customRender: 'class_' },
        },
        {
          title: '上课时间',
          dataIndex: 'time',
          width:230,
          scopedSlots: { customRender: 'time' },
        },
        {
          title: '上课老师',
          dataIndex: 'teachers',
          customRender(teachers) {
            if (teachers.length > 0) {
              return teachers.join('，')
            } else {
              return '--'
            }
          },
        },
        {
          title: '授课->核实课时',
          dataIndex: 'class_hour',
          scopedSlots: { customRender: 'classHour' },
        },

        {
          title: '课消金额',
          dataIndex: 'sum_class_consume',
          align: 'center',
          scopedSlots: { customRender: 'sum_class_consume' },
          // customRender(text) {
          //   return text ? '￥' + text : '暂无'
          // },
        },
        {
          title: '审核状态',
          align: 'center',
          scopedSlots: { customRender: 'verify_class_hour' },
        },
        {
          title: '实到人数',
          dataIndex: 'actual_number',
          align: 'center',
          scopedSlots: { customRender: 'actual_number' },
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          fixed: 'right',
          scopedSlots: { customRender: 'action' },
        },
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: (parameter) => {
        return callRecords(Object.assign(parameter, this.queryParam)).then((res) => {
          return res
        })
      },
      actionColumns: [
        {
          title: '操作时间',
          dataIndex: 'created_at',
        },
        {
          title: '操作人',
          dataIndex: 'class',
          scopedSlots: { customRender: 'class_' },
        },
        {
          title: '账号',
          dataIndex: 'time',
          scopedSlots: { customRender: 'time' },
        },
        {
          title: '操作类型',
          dataIndex: 'teachers',
          customRender(teachers) {
            if (teachers.length > 0) {
              return teachers.join('，')
            } else {
              return '--'
            }
          },
        },
        {
          title: '修改内容',
          dataIndex: 'actual_number',
          align: 'center',
          scopedSlots: { customRender: 'actual_number' },
        },
      ],
      actionData: (parameter) => {
        return callRecords(Object.assign(parameter, this.queryParam)).then((res) => {
          return res
        })
      },
      actionModelVisible: false,
    }
  },

  created() {},

  watch: {
    queryParam: {
      handler(val) {
        this.$refs.table.refresh(true)
      },
      deep: true,
    },
  },

  mounted() {
    // 获取老师信息

    teacherList({ pageSize: 999999, school_id: this.$store.state.user.school }).then((res) => {
      this.Isteacher = res.data
    })
    // 获取课程信息

    coursesList({ pageSize: 999999, school_id: this.$store.state.user.school }).then((res) => {
      this.Iscourses = res.data
    })

    // 获取班级信息
    classList({ pageSize: 999999, school_id: this.$store.state.user.school }).then((res) => {
      //搜索班级--keywords，名字字段
      this.Isclass = res.data
    })
  },

  methods: {
    moment,
    changeClassHour(data) {
      data.class_hour = +Number(data.class_hour)
      this.$forceUpdate()
    },
    showOrHidden(data, index) {
      data.flag = !data.flag
      this.tableData.splice(index, 1, data)
    },
    more() {
      this.showSearch = !this.showSearch
    },
    openstudent(data) {
      this.modaltitle = data.class.name
      this.peopleId = data.id
      this.loading = true
      this.reloadSignList(data.id)
    },
    reloadSignList(data,page = 1, pagesize = 10) {
      this.modalLoading = true
      callRecordsStudentList({ school_id: this.$store.state.user.school, pageNo: page, pageSize: pagesize }, data)
        .then((res) => {
          this.tableData = JSON.parse(JSON.stringify(res.data))
          this.tableData.forEach((item) => {
            item.flag = false
            item.daotype = item.type
          })
          this.tablevisible = true
          // this.$refs.actionTable.refresh()
          // this.actionModelVisible = true
          this.pageData=res.meta
        })
        .catch((err) => {
          this.$message.error(err.data.message || '获取失败')
        })
        .finally(() => {
          this.modalLoading = false
          this.loading = false
        })
    },
   changePage(page, pageSize) {
      this.page = page
      this.pageSize = pageSize
      this.reloadSignList(this.peopleId,page, pageSize)
    },
    //导出
    excelOut(type) {
      if (type == 'class') {
        this.loading = true
        orderNameExcelOutByClass(this.queryParam)
          .then((res) => {
            let url = res.url.url + res.url.path
            window.location.href = url
          })
          .catch((err) => {
            this.$message.error(err.data.message || '导出失败')
          })
          .finally(() => {
            this.loading = false
          })
      } else {
        this.loading = true
        orderNameExcelOut(this.queryParam)
          .then((res) => {
            let url = res.url.url + res.url.path
            window.location.href = url
          })
          .catch((err) => {
            this.$message.error(err.data.message || '导出失败')
          })
          .finally(() => {
            this.loading = false
          })
      }
    },
    // 列表删除
    table_del(e) {
      let that = this
      this.$confirm({
        title: '撤销点名记录',
        content: '撤销记录后，将退还学员课时',
        okText: '确定',
        okType: 'primary',
        cancelText: '取消',
        onOk() {
          callRecordsDelete(e.id)
            .then((res) => {
              that.$refs.table.refresh()
            })
            .catch((err) => {
              that.$message.error(err.data.message || '删除失败')
            })
        },
        onCancel() {},
      })
    },

    hourEdit(data) {
      this.IshourEdit_id = data.id
      if (!this.IshourEdit) {
        this.IshourEdit = !this.IshourEdit
      } else {
        editVerifyClassHour({ verify_class_hour: data.verify_class_hour }, data.id)
          .then((res) => {
            this.IshourEdit = !this.IshourEdit
            this.$refs.table.refresh()
          })
          .catch((err) => {
            this.$message.error(err.data.message || '修改失败')
          })
      }
    },
    timeEdit(val) {
      this.time_date = val
      this.visible = true
    },
    handleMenuClick(e) {
      this.isTypeEdit = e
    },
    typeEdit(record, index) {
      record.flag = !record.flag
      this.$forceUpdate()
    },
    saveStudentInfo(data, index) {
      this.modalLoading = true
      editOrderInfo(
        {
          type: Number(data.daotype),
          remarks: data.remarks,
          class_hour: data.consume_type == 1 ? data.class_hour : null,
        },
        data.id
      )
        .then((res) => {
          this.$message.success('修改成功')
          this.reloadSignList(this.peopleId)
        })
        .catch((err) => {
          this.$message.error(err.data.message || '修改失败')
        })
        .finally(() => {
          this.modalLoading = false
        })
    },
    onChangedate(moment, timeString) {
      this.new_attend_class_day = timeString
    },
    handleChangestart(moment, timeString) {
      this.new_start_time = timeString
    },
    handleChangeend(moment, timeString) {
      this.new_end_time = timeString
    },

    handleOk(e) {
      let id = this.time_date.id
      this.changeTimeloading = true
      if (this.new_attend_class_day === '') {
        this.new_attend_class_day = this.time_date.attend_class_day
      }
      if (this.new_start_time === '') {
        this.new_start_time = this.time_date.start_time
      }
      if (this.new_end_time === '') {
        this.new_end_time = this.time_date.end_time
      }
      editClassTime(
        { attend_class_day: this.new_attend_class_day, start_time: this.new_start_time, end_time: this.new_end_time },
        id
      )
        .then((res) => {
          this.changeTimeloading = false
          this.visible = false
          this.$refs.table.refresh()
        })
        .catch((err) => {
          this.changeTimeloading = false
          this.$message.error(err.data.message || '修改失败')
        })
    },
    handlemodal(e) {},
    onChangeverify(val) {
      console.log(`onChangeverify==== ${val}`)
      return
      this.$refs.table.refresh()
    },

    handleChange1(value, date) {
      this.datevalue1 = value
      this.queryParam.start_time = date[0]
      this.queryParam.end_time = date[1]
    },

    handleChange2(value, date) {
      this.datevalue2 = value
      this.queryParam.start_create_time = date[0]
      this.queryParam.end_create_time = date[1]
      this.$refs.table.refresh()
    },

    newSelect() {
      this.queryParam = {}
      this.datevalue1 = []
      this.datevalue2 = []
    },
  },
}
</script>
<style lang="less" scoped>
#aCardPosition {
  position: relative;
}
#moreButton {
  position: absolute;
  top: 34px;
  right: 20px;
}
.searchBtn {
  margin: 16px 20px 16px 0;
}
.tableTopActionBtns {
  padding-top: 16px;
  border-top: 1px solid #e8e8e8;
  button {
    margin: 0 20px 16px 0;
  }
}
.img_explain > div {
  display: inline-block;
  vertical-align: top;
}
.img_img {
  padding: 0 5px 5px 0;
}
.explain_explain {
  padding: 0 5px 5px 0;
}
.big_img {
  position: fixed;
  background-color: rgba(0, 0, 0, 0.7);
  width: 100vw;
  height: 100vh;
  top: 0;
  left: 0;
  z-index: 9999;
}
.big_imgcss {
  width: 30vh;
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  margin: auto;
}
#select_class {
  position: relative;
}
#select_class_a {
  position: relative;
}
#select_class_model {
  position: absolute;
  border: 1px solid rgb(165, 165, 165);
  z-index: 99999;
  background-color: white;
  height: 300px;
  border-radius: 5px;
  overflow-x: hidden;
  overflow-y: auto;
}
.excelModal {
  display: flex;
  justify-content: space-around;
  .left {
    text-align: center;
    width: 49%;
  }
  .right {
    text-align: center;
    width: 49%;
  }
}
</style>